//
//  PlatformViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/14.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "PlatformViewController.h"
#import "PlatformTabBarController.h"
#import "UIView+TransitionAnimation.h"
#import "IndexViewController.h"

@interface PlatformViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;

@property (weak, nonatomic) IBOutlet UIButton *accountBtn;

@property (weak, nonatomic) IBOutlet UIButton *vinBtn;

@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (strong, nonatomic) IBOutlet UIView *lineView1;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UILabel *lineView2;

@property (weak, nonatomic) IBOutlet UIButton *rememberBtn;

@property (nonatomic, strong) UIButton *selectBtn;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation PlatformViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 50.f;
    
    [self addAllConstraints];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    LoginType loginType = self.user.loginType;
    BOOL isSavePsd =  self.user.isSavePsd;
    
    if (self.user.isSavePsd){
        _rememberBtn.selected = YES;
    }
    
    if (loginType == LoginTypeAccount) {
        self.vinBtn.selected = NO;
        self.accountBtn.selected = YES;
        self.vinBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
        self.accountBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        
        if (isSavePsd) {
            self.accountTextField.text = self.user.account;
            self.passwordTextField.text = self.user.password;
        }
    } else{
        self.vinBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        self.accountBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
        self.accountBtn.selected = NO;
        self.vinBtn.selected = YES;
        if (isSavePsd) {
            self.accountTextField.text = self.user.vinAccount;
            self.passwordTextField.text = self.user.vinPassword;
        }
    }
}

- (void)setLoginBtn:(UIButton *)loginBtn {
    _loginBtn = loginBtn;
    if (@available(iOS 13.0, *)) {
        UIColor *loginColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBaseColor;
            } else {
                return kBaseColorDark20;
            }
        }];
        [_loginBtn setBackgroundColor:loginColor];
    } else {
        [_loginBtn setBackgroundColor:kBaseColor];
    }
}

- (void)setAccountBtn:(UIButton *)accountBtn {
    _accountBtn = accountBtn;
    [_accountBtn setTitleColor:kTextLightGrayColor forState:UIControlStateNormal];
    if (@available(iOS 13.0, *)) {
        [_accountBtn setTitleColor:UIColor.labelColor forState:UIControlStateSelected];
    } else {
        [_accountBtn setTitleColor:UIColor.blackColor forState:UIControlStateSelected];
    }
}

- (void)setVinBtn:(UIButton *)vinBtn {
    _vinBtn = vinBtn;
    [_vinBtn setTitleColor:kTextLightGrayColor forState:UIControlStateNormal];
    if (@available(iOS 13.0, *)) {
        [_vinBtn setTitleColor:UIColor.labelColor forState:UIControlStateSelected];
    } else {
        [_vinBtn setTitleColor:UIColor.blackColor forState:UIControlStateSelected];
    }
}

 // 切换登陆按钮
- (IBAction)changeLoginBtn:(UIButton *)btn
{
    if ([btn.titleLabel.text isEqualToString:@"车架号登录"]) {
        self.vinBtn.selected = YES;
        self.accountBtn.selected = NO;
        self.vinBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        self.accountBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
        self.accountTextField.placeholder = @"车架号";
        [self.user setLoginType:LoginTypeVin];
        if (self.user.isSavePsd){
            self.accountTextField.text = self.user.vinAccount;
            self.passwordTextField.text = self.user.vinPassword;
        }
    } else{
        self.vinBtn.selected = NO;
        self.accountBtn.selected = YES;
        self.accountBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 23);
        self.vinBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 16);
        [self.user setLoginType:LoginTypeAccount];
        self.accountTextField.placeholder = @"账号";
        if (self.user.isSavePsd){
            self.accountTextField.text = self.user.account;
            self.passwordTextField.text = self.user.password;
        }
    }
}

 // 登陆
- (IBAction)login:(id)sender
{
    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    // 账户登录
    if (self.accountBtn.selected)
    {
        if (self.accountTextField.text.length == 0 || self.passwordTextField.text.length <= 4) {
            [MBProgressHUD showToast:@"帐号或密码错误"];
        } else {
            [self.requestTool loginByAccount:self.accountTextField.text password:self.passwordTextField.text isSavePwd:self.user.isSavePsd success:^ (int status){
                if (status == 0) {
                    PlatformTabBarController *platform = [[PlatformTabBarController alloc] init];
                    [KEY_WINDOW addTransitionAnimationWithDuration:0.5f type:TransitionCube subType:FROM_TOP];
                    KEY_WINDOW.rootViewController = platform;
                } else {
                    [[[UIAlertView alloc] initWithTitle:@"账户或密码错误，请重新登录" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                }
            } failure:^(NSString *error) {
                PPLog(@"error = %@",error);
            }];
        }
    }
    else
    {// 车架号登录
        if (self.accountTextField.text.length == 0 || self.passwordTextField.text.length <= 5) {
            [MBProgressHUD showToast:@"车架号或密码错误"];
            return;
        }
        [self.requestTool loginByVin:self.accountTextField.text password:self.passwordTextField.text isSavePwd:self.user.isSavePsd success:^(int status,NSArray *equipmentList) {
            if (status == 0) {//KNAFW6112A5230062
                NSMutableArray *trackArray = [NSMutableArray array];
                for (EquipmentModel *eModel in equipmentList) {// 防止point是null,MJExtension返回@""的情况
                    if (![eModel.pointModel isKindOfClass:[NSString class]] && eModel.pointModel.lat && eModel.pointModel.lng) {
                        [trackArray addObject:eModel];
                    }
                }
                
                if (!trackArray.count) {// 没有定位的设备
                    [[[UIAlertView alloc] initWithTitle:@"设备未定位，请定位后重新登录" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                } else {
                    NSMutableArray *ableArray = [NSMutableArray array];
                    for (EquipmentModel *eModel in trackArray) {
                        if (![eModel.mark isEqualToString:@"D"]) {
                            [ableArray addObject:eModel];
                        }
                    }
                    
                    if (!ableArray.count) {// 没有可用的设备
                        [[[UIAlertView alloc] initWithTitle:@"该设备已被禁用" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                    } else {
                        IndexViewController *i = [[IndexViewController alloc] init];
                        i.dataSource = [NSMutableArray arrayWithArray:ableArray];
                        [self.navigationController pushViewController:i animated:YES];
                    }
                }
            } else
            {
                [[[UIAlertView alloc] initWithTitle:@"车架号或密码错误，请重新输入" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
            }
        } failure:^(NSError *error) {
            PPLog(@"vin login = %@",error.description);
        }];
    }
}

 // 记住密码
- (IBAction)remember:(id)sender {
    _rememberBtn.selected = !_rememberBtn.selected;
    
//    UIImage *image = _rememberBtn.imageView.image;
//    [_rememberBtn setImage:[UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationRight] forState:UIControlStateNormal];
    
    if (_rememberBtn.selected) {
        [self.user setSaveValue:@(1)];
    } else {
        [self.user setSaveValue:@(0)];
    }
}

- (void)addAllConstraints
{
    _scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:_scrollView];
    
    _scrollView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [_scrollView sd_addSubviews:@[_logoImgView,_accountBtn,_vinBtn,_accountTextField,_lineView1,_passwordTextField,_lineView2,_rememberBtn,_loginBtn]];
    
    CGFloat margin10 = 10; CGFloat margin15 = 15;
    CGFloat margin20 = 20; CGFloat margin30 = 30;
    
    _logoImgView.sd_layout
    .leftEqualToView(_scrollView)
    .rightEqualToView(_scrollView)
    .topEqualToView(_scrollView)
    .autoHeightRatio(0.63);
    
    _accountBtn.sd_layout
    .leftSpaceToView(_scrollView, margin30)
    .topSpaceToView(_logoImgView, margin20*2)
    .heightIs(margin30)
    .widthIs(margin30*5);
    
    _vinBtn.sd_layout
    .centerYEqualToView(_accountBtn)
    .rightSpaceToView(_scrollView, margin30)
    .heightRatioToView(_accountBtn, 1)
    .widthRatioToView(_accountBtn, 1);
    
    _accountTextField.sd_layout
    .topSpaceToView(_accountBtn, margin30)
    .leftEqualToView(_accountBtn)
    .rightEqualToView(_vinBtn)
    .heightIs(35);
    
    _lineView1.sd_layout
    .leftEqualToView(_accountTextField)
    .rightEqualToView(_vinBtn)
    .topSpaceToView(_accountTextField, margin10)
    .heightIs(1);
    
    _passwordTextField.sd_layout
    .leftEqualToView(_lineView1)
    .rightEqualToView(_lineView1)
    .topSpaceToView(_lineView1, margin10)
    .heightRatioToView(_accountTextField, 1);
    
    _lineView2.sd_layout
    .leftEqualToView(_passwordTextField)
    .rightEqualToView(_passwordTextField)
    .topSpaceToView(_passwordTextField, margin10)
    .heightIs(1);
    
    _rememberBtn.sd_layout
    .topSpaceToView(_lineView2, margin10)
    .leftEqualToView(_lineView2)
    .heightIs(25);
    
//    _rememberBtn.imageView.sd_layout
//    .leftSpaceToView(_rememberBtn, 0)
//    .topSpaceToView(_rememberBtn, 0)
//    .bottomSpaceToView(_rememberBtn, 0)
//    .widthIs(25);
    
    _loginBtn.sd_layout
    .topSpaceToView(_rememberBtn, kAutoHeight(margin20*2.5))
    .leftEqualToView(_lineView2)
    .rightEqualToView(_lineView2)
    .heightIs(45);
    
    [_scrollView setupAutoContentSizeWithBottomView:_loginBtn bottomMargin:margin20*2];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
